<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品类别管理</el-breadcrumb-item>
      <el-breadcrumb-item v-for="item in history" :key="item.id"><span v-text="item.name"></span></el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <div style="margin-bottom: 20px">
      <el-button type="primary" round size="medium" @click="$router.push('/sys-admin/product/category/add-new')">添加商品类别</el-button>
      <div v-if="currentParentId !== 0" style="float: right; margin-right: 40px">
        <el-button size="medium"  @click="goBack()">返回</el-button>
      </div>
    </div>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="100" align="center"></el-table-column>
      <el-table-column prop="name" label="名称" width="150" header-align="center"></el-table-column>
      <el-table-column prop="icon" label="图标" width="100" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.icon" width="40" height="40"/>
        </template>
      </el-table-column>
      <el-table-column prop="keywords" label="关键词" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sort" label="排序序号" width="100" align="center"></el-table-column>
      <el-table-column prop="enable" label="是否启用" width="150" align="center">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.enable"
              @change="setEnable(scope.row)"
              active-color="#13ce66"
              inactive-color="#ccc"
              :active-value="1"
              :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="isDisplay" label="是否展示" width="150" align="center">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.isDisplay"
              @change="setIsDisplay(scope.row)"
              active-color="#13ce66"
              inactive-color="#ccc"
              :active-value="1"
              :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="查看子级" width="150" align="center">
        <template slot-scope="scope">
          <el-button size="mini" :disabled="scope.row.isParent === 0" @click="showSubCategoryList(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" circle @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" circle :disabled="scope.row.isParent === 1" @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right; margin: 10px auto;">
      <el-pagination
          background
          @current-change="changePage"
          layout="total, prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize">
      </el-pagination>
    </div>

    <el-dialog title="修改类别" :visible.sync="dialogFormVisible">
      <el-form :model="editForm" :rules="rules" ref="ruleForm" label-width="100px">

        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="图标" prop="icon">
          <el-input v-model="editForm.icon" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="关键词" prop="keywords">
          <el-input v-model="editForm.keywords" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editForm.sort" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="是否启用" prop="enable">
          <el-switch
              :active-value="1"
              :inactive-value="0"
              v-model="editForm.enable"
              disabled
              active-color="#13ce66"
              inactive-color="#ccc">
          </el-switch>
        </el-form-item>

        <el-form-item label="是否展示" prop="isDisplay">
          <el-switch
              :active-value="1"
              :inactive-value="0"
              v-model="editForm.isDisplay"
              disabled
              active-color="#13ce66"
              inactive-color="#ccc">
          </el-switch>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdate()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
let localJwt = localStorage.getItem('localJwt');
export default {
  data() {
    return {
      tableData: [],
      total: 0,
      pageSize: 0,
      currentPage: 1,
      // 编辑对话框的可见性
      dialogFormVisible: false,
      // 当前类别列表的父级类别ID
      currentParentId: 0,
      // 浏览历史，此数据主要用于返回功能
      history: [],
      editForm: {
        id: '',
        name: '',
        icon: '',
        keywords: '',
        sort: '',
        enable: '',
        isDisplay: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 25, message: '长度在 1 到 25 个字符', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '请输入头像', trigger: 'blur' }
        ],
        keywords: [
          { required: true, message: '请输入关键词', trigger: 'blur' },
          { min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序序号', trigger: 'blur' },
          { pattern: /^(\d{1}|[1-9]{1}[0-9]{1})$/, message: '排序序号必须是0~99之间的整数', trigger: 'blur' }
        ],
        enable: [],
        isDisplay: []
      }
    }
  },
  methods: {
    changePage(value) {
      this.$router.replace('?page=' + value);
      this.loadCategoryList();
    },
    loadCategoryList() {
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }
      let url = "http://localhost:8080/category/list-by-parent?page=" + page + "&parentId=" + this.currentParentId;
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    showSubCategoryList(category) {
      this.history[category.depth - 1] = category;
      this.currentParentId = category.id;
      this.loadCategoryList();
    },
    goBack() {
      let parentCategory = this.history[this.history.length - 1];
      this.currentParentId = parentCategory.parentId;
      this.loadCategoryList();
      this.history.pop();
    },
    openEditDialog(category) {
      let url = "http://localhost:8080/category/getStandardById/" + category.id;
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadCategoryList();
            }
          });
        }
      });
    },
    handleUpdate() {
      // 要发送到后端的地址
      let url = "http://localhost:8080/category/updateInfoById";
      let formData = this.qs.stringify(this.editForm);// 通过qs转换格式（从对象转换为formData）
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url, formData).then((response) => {// 后端那边为updateInfoById(Long id, AlbumUpdateInfoParam albumUpdateInfoParam)
        // 虽然有两个参数，但是前端传过去的 formData 是一整个 id=24&name=xx&description=xx&sort=99
        // Controller应该能自动匹配参数
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.$message({
            message: '修改类别成功！',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.loadCategoryList();
        } else if (jsonResult.state === 404){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadCategoryList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    setEnable(category) {
      let enableText = ['禁用', '启用'];
      let url = "http://localhost:8080/category/" + category.id + "/setEnable";
      let enable = category.enable;
      if (enable === 1) {
        url += '?enable=1';
      } else {
        url += '?enable=0';
      }
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.$message({
            message: '将【' + category.name + '】的启用状态修改为【' + enableText[enable] + '】成功！',
            type: 'success'
          });
          this.loadCategoryList();
        } else if (jsonResult.state === 404) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadCategoryList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(err => {
        let message = '服务器响应错误！';
        this.$alert(message, '操作失败', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      });
    },
    setIsDisplay(category) {
      let isDisplayText = ['不展示', '展示'];
      let url = "http://localhost:8080/category/" + category.id + "/setIsDisplay";
      let isDisPlay = category.isDisplay;
      if (isDisPlay === 1) {
        url += '?isDisplay=1';
      } else {
        url += '?isDisplay=0';
      }
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.$message({
            message: '将【' + category.name + '】的展示状态修改为【' + isDisplayText[isDisPlay] + '】成功！',
            type: 'success'
          });
          this.loadCategoryList();
        } else if (jsonResult.state === 404) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadCategoryList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(err => {
        let message = '服务器响应错误！';
        this.$alert(message, '操作失败', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      });
    },
    openDeleteConfirm(category) {
      this.$confirm('此操作将永久删除【' + category.id + '-' + category.name + '】类别, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(category);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleDelete(category) {
      let url = "http://localhost:8080/category/delete?categoryId=" + category.id;
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          this.loadCategoryList();
        } else if (jsonResult.state === 404){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminList();
            }
          });
        } else if (jsonResult.state === 409){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(err => {
        let message = '服务器响应错误！';
        this.$alert(message, '操作失败', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      });
    }
  },
  mounted() {
    this.loadCategoryList();
  }
}
</script>
